package com.system.vote.admin.controller;

import com.auth0.jwt.interfaces.Claim;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.system.vote.admin.entity.SysAccount;
import com.system.vote.admin.entity.SysLoginLog;
import com.system.vote.admin.entity.SysOffMessage;
import com.system.vote.admin.entity.TVote;
import com.system.vote.admin.security.JwtUtil;
import com.system.vote.admin.service.SysLoginLogService;
import com.system.vote.admin.service.SysOffMessageService;
import com.system.vote.admin.service.SysOperationLogService;
import com.system.vote.admin.service.TVoteService;
import com.system.vote.common.utils.DateUtil;
import com.system.vote.core.http.Result;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@Api(tags = "PC后台仪表盘")
@Slf4j
@RequestMapping("/dashboard")
public class SysDashBoardController {
    @Autowired
    private SysOperationLogService sysOperationLogService;

    @Autowired
    private TVoteService tVoteService;

    @Autowired
    private SysLoginLogService sysLoginLogService;

    @Autowired
    private SysOffMessageService sysOffMessageService;



    /**
     * 用户累计浏览量
     *
     * @return
     */
    @GetMapping("/userViews")
    @ApiOperation(value = "用户累计浏览量统计")
    public Result countUserViews() {
        return Result.success(sysOperationLogService.count());
    }

    /**
     * 投票主题数量
     *
     * @return
     */
    @GetMapping("/tvoteCount")
    @ApiOperation(value = "投票主题数量统计")
    public Result countTvote() {
        return Result.success(tVoteService.count(new QueryWrapper<TVote>().eq("status", "0")));
    }

    /**
     * 用户累计数量
     *
     * @return
     */
    @GetMapping("/userCount")
    @ApiOperation(value = "用户累计数量统计")
    public Result countUser() {
        return Result.success(sysLoginLogService.count(new QueryWrapper<SysLoginLog>().select("distinct name")));
    }

    /**
     * 系统消息数量
     *
     * @return
     */
    @GetMapping("/messageCount")
    @ApiOperation(value = "系统消息数量统计")
    public Result countMessage() {
        return Result.success(sysOffMessageService.count());
    }

    /**
     * 投票种类
     *
     * @return
     */
    @GetMapping("/tVoteTypeCount")
    @ApiOperation(value = "投票主题分类统计")
    public Result countTVoteType() {
        List<TVote> tVoteList = tVoteService.list(new QueryWrapper<TVote>().eq("status", "0"));
        long textCount = tVoteList.stream().filter(vote -> vote.getType() == 1).count();
        long picCount = tVoteList.stream().filter(vote -> vote.getType() == 2).count();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("total", tVoteList.size());
        resultMap.put("textCount", textCount);
        resultMap.put("picCount", picCount);
        double textPercentage = (double) textCount / tVoteList.size() * 100; // 将浮点数转换为百分比
        double picPercentage = (double) picCount / tVoteList.size() * 100; // 将浮点数转换为百分比

        DecimalFormat df = new DecimalFormat("#.00");
        if (tVoteList.size() > 0) {
            resultMap.put("textPercent", df.format(textPercentage));
            resultMap.put("picPercent", df.format(picPercentage));
        }
        return Result.success(resultMap);
    }

    @GetMapping("/tVoteTypeWeek/{count}")
    @ApiOperation(value = "最近几天投票分类统计")
    public Result tVoteTypeWeek(@PathVariable("count") int count) {
        List<Map<String, Object>> recentDateRange = DateUtil.getRecentDateRange("day", count);
        List<String> dayOfYear = new ArrayList<>();
        List<Long> texts = new ArrayList<>();
        List<Long> pics = new ArrayList<>();
        for (Map<String, Object> days : recentDateRange
        ) {
            Date startDate = (Date) days.get("startDate");
            Date endDate = (Date) days.get("endDate");
            List<TVote> tVoteList = tVoteService.list(new QueryWrapper<TVote>().eq("status", '0').between("create_time", startDate, endDate));
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            dayOfYear.add(month + "月" + day + "日");

            if (tVoteList.size() > 0) {
                long textCount = tVoteList.stream().filter(vote -> vote.getType() == 1).count();
                texts.add(textCount);
                long picCount = tVoteList.stream().filter(vote -> vote.getType() == 2).count();
                pics.add(picCount);
            } else {
                texts.add(0L);
                pics.add(0L);
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("days", dayOfYear);
        result.put("texts", texts);
        result.put("pics", pics);
        return Result.success(result);
    }

    @GetMapping("/tVoteTypeMonth/{count}")
    @ApiOperation(value = "最近几月投票分类统计")
    public Result tVoteTypeMonth(@PathVariable("count") int count) {
        List<Map<String, Object>> recentDateRange = DateUtil.getRecentDateRange("month", count);
        System.out.println(recentDateRange.toString());
        List<String> months = new ArrayList<>();
        List<Long> texts = new ArrayList<>();
        List<Long> pics = new ArrayList<>();
        for (Map<String, Object> days : recentDateRange
        ) {
            Date startDate = (Date) days.get("startDate");
            System.out.println("startOfDay:" + startDate);
            Date endDate = (Date) days.get("endDate");
            System.out.println("endOfDay:" + endDate);

            List<TVote> tVoteList = tVoteService.list(new QueryWrapper<TVote>().eq("status", '0').between("create_time", startDate, endDate));
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            int month = calendar.get(Calendar.MONTH);

            months.add(String.valueOf(month + 1) + "月");

            if (tVoteList.size() > 0) {
                long textCount = tVoteList.stream().filter(vote -> vote.getType() == 1).count();
                texts.add(textCount);
                long picCount = tVoteList.stream().filter(vote -> vote.getType() == 2).count();
                pics.add(picCount);
            } else {
                texts.add(0L);
                pics.add(0L);
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("months", months);
        result.put("texts", texts);
        result.put("pics", pics);
        return Result.success(result);
    }


    @GetMapping("/getLastLoginAddress")
    @ApiOperation(value = "获取登录地址")
    public Result getLastLoginAddress(HttpServletRequest request) {
        String token = request.getHeader("token");
        Claims claim = JwtUtil.parseJWT(token);
        Page<SysLoginLog> pageResult = sysLoginLogService.page(
                new Page<>(1, 1)
                , new LambdaQueryWrapper<SysLoginLog>()
                        .eq(SysLoginLog::getType, 1)
                        .and(e -> e.eq(SysLoginLog::getUid, claim.getId()))
                        .orderByDesc(SysLoginLog::getCreateTime)

        );
        List<SysLoginLog> sysLoginLogs = pageResult.getRecords();
        return Result.success(sysLoginLogs);
    }
}
